/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.asyncexecutor.multitenant;

import com.je.bpm.engine.impl.asyncexecutor.DefaultAsyncJobExecutor;
import com.je.bpm.engine.impl.asyncexecutor.ExecuteAsyncRunnableFactory;
import com.je.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import com.je.bpm.engine.impl.cfg.multitenant.TenantInfoHolder;
import com.je.bpm.engine.runtime.Job;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;

/**
 * Multi tenant {@link AsyncExecutor}.
 * <p>
 * For each tenant, there will be acquire threads, but only one {@link ExecutorService} will be used
 * once the jobs are acquired.
 */
public class SharedExecutorServiceAsyncExecutor extends DefaultAsyncJobExecutor implements TenantAwareAsyncExecutor {

    private static final Logger logger = LoggerFactory.getLogger(SharedExecutorServiceAsyncExecutor.class);

    protected TenantInfoHolder tenantInfoHolder;

    protected Map<String, Thread> timerJobAcquisitionThreads = new HashMap<String, Thread>();
    protected Map<String, TenantAwareAcquireTimerJobsRunnable> timerJobAcquisitionRunnables
            = new HashMap<String, TenantAwareAcquireTimerJobsRunnable>();

    protected Map<String, Thread> asyncJobAcquisitionThreads = new HashMap<String, Thread>();
    protected Map<String, TenantAwareAcquireAsyncJobsDueRunnable> asyncJobAcquisitionRunnables
            = new HashMap<String, TenantAwareAcquireAsyncJobsDueRunnable>();

    protected Map<String, Thread> resetExpiredJobsThreads = new HashMap<String, Thread>();
    protected Map<String, TenantAwareResetExpiredJobsRunnable> resetExpiredJobsRunnables
            = new HashMap<String, TenantAwareResetExpiredJobsRunnable>();

    public SharedExecutorServiceAsyncExecutor(TenantInfoHolder tenantInfoHolder) {
        this.tenantInfoHolder = tenantInfoHolder;

        setExecuteAsyncRunnableFactory(new ExecuteAsyncRunnableFactory() {

            @Override
            public Runnable createExecuteAsyncRunnable(Job job, ProcessEngineConfigurationImpl processEngineConfiguration) {

                // Here, the runnable will be created by for example the acquire thread, which has already set the current id.
                // But it will be executed later on, by the executorService and thus we need to set it explicitely again then

                return new TenantAwareExecuteAsyncRunnable(job, processEngineConfiguration,
                        SharedExecutorServiceAsyncExecutor.this.tenantInfoHolder,
                        SharedExecutorServiceAsyncExecutor.this.tenantInfoHolder.getCurrentTenantId());
            }

        });
    }

    @Override
    public Set<String> getTenantIds() {
        return timerJobAcquisitionRunnables.keySet();
    }

    @Override
    public void addTenantAsyncExecutor(String tenantId, boolean startExecutor) {

        TenantAwareAcquireTimerJobsRunnable timerRunnable = new TenantAwareAcquireTimerJobsRunnable(this, tenantInfoHolder, tenantId);
        timerJobAcquisitionRunnables.put(tenantId, timerRunnable);
        timerJobAcquisitionThreads.put(tenantId, new Thread(timerRunnable));

        TenantAwareAcquireAsyncJobsDueRunnable asyncJobsRunnable = new TenantAwareAcquireAsyncJobsDueRunnable(this, tenantInfoHolder, tenantId);
        asyncJobAcquisitionRunnables.put(tenantId, asyncJobsRunnable);
        asyncJobAcquisitionThreads.put(tenantId, new Thread(asyncJobsRunnable));

        TenantAwareResetExpiredJobsRunnable resetExpiredJobsRunnable = new TenantAwareResetExpiredJobsRunnable(this, tenantInfoHolder, tenantId);
        resetExpiredJobsRunnables.put(tenantId, resetExpiredJobsRunnable);
        resetExpiredJobsThreads.put(tenantId, new Thread(resetExpiredJobsRunnable));

        if (startExecutor) {
            startTimerJobAcquisitionForTenant(tenantId);
            startAsyncJobAcquisitionForTenant(tenantId);
            startResetExpiredJobsForTenant(tenantId);
        }
    }

    @Override
    public void removeTenantAsyncExecutor(String tenantId) {
        stopThreadsForTenant(tenantId);
    }

    @Override
    public void start() {
        for (String tenantId : timerJobAcquisitionRunnables.keySet()) {
            startTimerJobAcquisitionForTenant(tenantId);
            startAsyncJobAcquisitionForTenant(tenantId);
            startResetExpiredJobsForTenant(tenantId);
        }
    }

    protected void startTimerJobAcquisitionForTenant(String tenantId) {
        timerJobAcquisitionThreads.get(tenantId).start();
    }

    protected void startAsyncJobAcquisitionForTenant(String tenantId) {
        asyncJobAcquisitionThreads.get(tenantId).start();
    }

    protected void startResetExpiredJobsForTenant(String tenantId) {
        resetExpiredJobsThreads.get(tenantId).start();
    }

    @Override
    protected void stopJobAcquisitionThread() {
        for (String tenantId : timerJobAcquisitionRunnables.keySet()) {
            stopThreadsForTenant(tenantId);
        }
    }

    protected void stopThreadsForTenant(String tenantId) {
        timerJobAcquisitionRunnables.get(tenantId).stop();
        asyncJobAcquisitionRunnables.get(tenantId).stop();
        resetExpiredJobsRunnables.get(tenantId).stop();

        try {
            timerJobAcquisitionThreads.get(tenantId).join();
        } catch (InterruptedException e) {
            logger.warn("Interrupted while waiting for the timer job acquisition thread to terminate", e);
        }

        try {
            asyncJobAcquisitionThreads.get(tenantId).join();
        } catch (InterruptedException e) {
            logger.warn("Interrupted while waiting for the timer job acquisition thread to terminate", e);
        }

        try {
            resetExpiredJobsThreads.get(tenantId).join();
        } catch (InterruptedException e) {
            logger.warn("Interrupted while waiting for the reset expired jobs thread to terminate", e);
        }
    }

}
